package com.example.ImageSelect;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import de.greenrobot.event.EventBus;

public class MyActivity extends Activity {
    private ListView listView;
    private AlbumListViewAdapter listViewAdapter;
    private ArrayList<Album> albums;

    private GridView gridView;
    private GridViewAdapter gridViewAdapter;
    private ArrayList<String> mPhotos = new ArrayList<String>();
    private ArrayList<String> mSelectedPhotos = new ArrayList<String>();
    private HashMap<String,ImageView> hashMap = new HashMap<String,ImageView>();

    private LinearLayout selectedImageLayout;
    private HorizontalScrollView scroll_view;
    private Button btn_album;
    private Button btn_cancel;
    private TextView title;
    private Button okButton;

    private EventBus eventBus;
    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        eventBus = EventBus.getDefault();
        eventBus.register(this);

        listView = (ListView) this.findViewById(R.id.list_view);
        gridView = (GridView) this.findViewById(R.id.grid_view);
        listViewAdapter = new AlbumListViewAdapter(getApplicationContext());

        selectedImageLayout = (LinearLayout)findViewById(R.id.selected_image_layout);
        scroll_view = (HorizontalScrollView)findViewById(R.id.scrollview);
        btn_album = (Button) this.findViewById(R.id.photo);
        btn_cancel = (Button) this.findViewById(R.id.cancel);
        title = (TextView) this.findViewById(R.id.title);
        okButton = (Button) this.findViewById(R.id.ok_button);
        btn_album.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                listView.setVisibility(View.VISIBLE);
                gridView.setVisibility(View.INVISIBLE);
                btn_album.setVisibility(View.INVISIBLE);
                title.setText("相册");
            }
        });

        albums = getAlbums();
        listViewAdapter.setAlbumsList(albums);
        listView.setAdapter(listViewAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                TestEvent event = new TestEvent("list_view_item_click");
                Bundle bundle = new Bundle();
                bundle.putInt("position", i);
                event.set_bundle(bundle);
                eventBus.post(event);
            }
        });
    }

    public ArrayList<Album> getAlbums()
    {
        ArrayList<Album> albums = new ArrayList<Album>();
        ContentResolver contentResolver = getContentResolver();
        String[] projection = new String[] { MediaStore.Images.Media.DATA };
        Cursor cursor = contentResolver.query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null,
                null, MediaStore.Images.Media.DEFAULT_SORT_ORDER);
        cursor.moveToFirst();
        int fileNum = cursor.getCount();

        for (int counter = 0; counter < fileNum; counter++) {
            Log.w("tag", "---file is:" + cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA)));
            String path = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA));
            //获取路径中文件的目录
            String file_dir = Util.getDir(path);

            //判断该目录是否已经存在于albums中，如果存在，则不添加到albums中；不存在则添加。
            boolean in_albums = false;//默认不存在于albums中
            for (Album temp_album : albums)
            {
                if(temp_album.mName.equals(file_dir))
                {
                    //存在于albums中
                    in_albums = true;
                    break;
                }
            }

            if(!in_albums)
            {
                Album album = new Album();
                album.mName = Util.getDir(path);
                album.mNum = "(" + getPicNum(album.mName) + ")";
                album.mCoverUrl = path;
                albums.add(album);
            }
            cursor.moveToNext();
        }
        cursor.close();

        return albums;
    }

    public int getPicNum(String album_file_dir)
    {
        ContentResolver contentResolver = getContentResolver();
        String[] projection = new String[] { MediaStore.Images.Media.DATA };
        Cursor cursor = contentResolver.query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null,
                null, MediaStore.Images.Media.DEFAULT_SORT_ORDER);
        cursor.moveToFirst();
        int fileNum = cursor.getCount();

        int photo_num = 0;
        for (int counter = 0; counter < fileNum; counter++) {
            Log.w("tag", "---file is:" + cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA)));
            String path = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA));
            //获取路径中文件的目录
            String file_dir = Util.getDir(path);

            if(album_file_dir.equals(file_dir))
                photo_num++;
            cursor.moveToNext();
        }
        cursor.close();
        return photo_num;
    }

    public ArrayList<String> getPhotos(String album_dir)
    {
        ArrayList<String> photos = new ArrayList<String>();
        ContentResolver contentResolver = getContentResolver();
        String[] projection = new String[] { MediaStore.Images.Media.DATA };
        Cursor cursor = contentResolver.query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null,
                null, MediaStore.Images.Media.DEFAULT_SORT_ORDER);
        cursor.moveToFirst();
        int fileNum = cursor.getCount();

        for (int counter = 0; counter < fileNum; counter++) {
            Log.w("tag", "---file is:" + cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA)));
            String path = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA));
            //获取路径中文件的目录
            String file_dir = Util.getDir(path);
            if(file_dir.equals(album_dir))
                photos.add(path);
            cursor.moveToNext();
        }
        cursor.close();

        return photos;
    }

    private boolean removePath(String path){
        if(hashMap.containsKey(path)){
            selectedImageLayout.removeView(hashMap.get(path));
            hashMap.remove(path);
            removeOneData(mSelectedPhotos,path);
            okButton.setText("完成("+mSelectedPhotos.size()+"/8)");
            return true;
        }else{
            return false;
        }
    }

    private void removeOneData(ArrayList<String> arrayList,String s){
        for(int i =0;i<arrayList.size();i++){
            if(arrayList.get(i).equals(s)){
                arrayList.remove(i);
                return;
            }
        }
    }

    //eventbus接收到通知事件，发生改变
    public void onEvent(TestEvent event) {
        if (event.get_string().equals("list_view_item_click"))
        {
            Bundle bundle = event.get_bundle();

            listView.setVisibility(View.INVISIBLE);
            gridView.setVisibility(View.VISIBLE);
            btn_album.setVisibility(View.VISIBLE);
            String album_dir = albums.get(bundle.getInt("position")).mName;
            title.setText(album_dir);
            mPhotos = getPhotos(album_dir);
            gridViewAdapter = new GridViewAdapter(getApplicationContext(), mPhotos, mSelectedPhotos);
            gridView.setAdapter(gridViewAdapter);
            gridViewAdapter.setOnItemClickListener(new GridViewAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(final ToggleButton toggleButton, int position, final String path,boolean isChecked) {
                    if(mSelectedPhotos.size() >= 8){
                        toggleButton.setChecked(false);
                        if(!removePath(path)){
                            Toast.makeText(MyActivity.this, "只能选择8张图片", 200).show();
                        }
                        return;
                    }

                    if(isChecked){
                        if(!hashMap.containsKey(path)){
                            ImageView imageView = (ImageView) LayoutInflater.from(MyActivity.this).inflate(R.layout.choose_imageview, selectedImageLayout, false);
                            selectedImageLayout.addView(imageView);
                            imageView.postDelayed(new Runnable() {
                                @Override
                                public void run() {

                                    int off = selectedImageLayout.getMeasuredWidth() - scroll_view.getWidth();
                                    if (off > 0) {
                                        scroll_view.smoothScrollTo(off, 0);
                                    }

                                }
                            }, 100);

                            hashMap.put(path, imageView);
                            mSelectedPhotos.add(path);
                            Constants.imageLoader.displayImage("file://" + mPhotos.get(position), imageView, Constants.image_display_options, new Util.AnimateFirstDisplayListener());
                            imageView.setOnClickListener(new View.OnClickListener() {

                                @Override
                                public void onClick(View v) {
                                    toggleButton.setChecked(false);
                                    removePath(path);

                                }
                            });
                            okButton.setText("完成("+mSelectedPhotos.size()+"/8)");
                        }
                    }else{
                        removePath(path);
                    }
                }
            });
        }
    }
}
